from PySide6.QtWidgets import QWidget, QVBoxLayout, QTreeView, QSizePolicy, QLabel, QTreeWidget, QTreeWidgetItem, QMenu, QInputDialog, QDialog, QHBoxLayout, QPushButton, QLineEdit,QMessageBox
from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QIcon
from terminal.ui import Terminal
from terminal.tabs import TabManager
from theme.manager import ThemeManager
import os
import re

class VersionManagerTab(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.version_info=''
        self.patch_info=''
        self.terminal=None

    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(24, 24, 24, 24)
        layout.setSpacing(16)

        # 设备信息区域
        info_container = QWidget()
        info_layout = QVBoxLayout(info_container)
        info_layout.setSpacing(8)

        # 设备型号
        model_label = QLabel("设备型号：")
        model_label.setObjectName("info_label")
        self.model_value = QLabel("未获取")
        model_layout = QHBoxLayout()
        model_layout.addWidget(model_label)
        model_layout.addWidget(self.model_value)
        model_layout.addStretch()
        info_layout.addLayout(model_layout)

        # 设备版本
        version_label = QLabel("设备版本：")
        version_label.setObjectName("info_label")
        self.version_value = QLabel("未获取")
        version_layout = QHBoxLayout()
        version_layout.addWidget(version_label)
        version_layout.addWidget(self.version_value)
        version_layout.addStretch()
        info_layout.addLayout(version_layout)

        # 设备补丁
        patch_label = QLabel("设备补丁：")
        patch_label.setObjectName("info_label")
        self.patch_value = QLabel("未获取")
        patch_layout = QHBoxLayout()
        patch_layout.addWidget(patch_label)
        patch_layout.addWidget(self.patch_value)
        patch_layout.addStretch()
        info_layout.addLayout(patch_layout)

        layout.addWidget(info_container)
        layout.addStretch()

        # 获取信息按钮
        button_layout = QHBoxLayout()
        get_info_button = QPushButton("获取设备信息")
        get_info_button.setObjectName("primaryButton")
        get_info_button.clicked.connect(self.get_device_info)
        button_layout.addStretch()
        button_layout.addWidget(get_info_button)
        layout.addLayout(button_layout)

    def get_device_info(self):
        """获取活动会话的设备信息"""
        # 获取主窗口实例
        main_window = None
        # 首先尝试通过parent()获取父窗口
        parent = self.parent()
        while parent:
            if parent.objectName() == "main_splitter":
                main_window = parent.window()
                break
            parent = parent.parent()
        
        # 如果通过父窗口链没有找到，则尝试从顶层窗口中查找
        if not main_window:
            for widget in QApplication.topLevelWidgets():
                if widget.objectName() == "central_widget":
                    main_window = widget.window()
                    break
                    
        if not main_window:
            return
            
        # 获取当前活动的终端标签页管理器
        tab_manager = None
        center_container = main_window.findChild(QWidget, "center_container")
        if center_container:
            tab_manager = center_container.findChild(TabManager, "session_content")

        if not tab_manager or tab_manager.count() == 0:
            QMessageBox.warning(self, '获取设备信息失败', '没有可用的终端会话，请先打开一个终端会话。')
            return
        
        # 获取当前活动的终端实例
        current_tab = tab_manager.currentWidget()
        if not current_tab:
            return

        self.terminal = current_tab.findChild(Terminal)
        if not self.terminal:
            return

        # 发送命令获取设备信息
        if self.terminal.connection_thread and self.terminal.connection_thread.is_connected():
            self.terminal.connection_thread.write('display version \n')
            # 连接终端输出信号
            self.terminal.connection_thread.received.connect(self.handle_version_output)

    def handle_version_output(self, output):
        # 处理输出内容，移除空格和换行符
        processed_output = output.replace(' ', '').replace('\r\n', '')
        
        # 将处理后的内容追加到version_info
        self.version_info += processed_output
        
        # 检查是否包含终止字符
        if '>' in output or ']' in output:
            print(f'Version info: {self.version_info}')
            
            # 提取设备型号
            model_match = re.search(r'(?i)HUAWEI(S\d+\-\d+X?\-[\w\-]+|AR\d+\w+\-\w+)(?=.*Rout|$)', self.version_info)
            if model_match:
                device_model = model_match.group(1)
                self.model_value.setText(device_model)
            
            # 提取版本号
            version_match = re.search(r'\((\w+)(V[\w\d]+)\)', self.version_info)
            if version_match:
                version_number = version_match.group(2)
                self.version_value.setText(version_number)
            
            # 断开与终端输出信号的连接并发送补丁信息命令
            if hasattr(self, 'terminal') and self.terminal and self.terminal.connection_thread:
                self.version_info = '' # 重置version_info
                self.terminal.connection_thread.received.disconnect(self.handle_version_output)
                # 发送补丁信息命令
                self.terminal.connection_thread.write('display patch-information \n')
                self.terminal.connection_thread.received.connect(self.handle_patch_output)

    def handle_patch_output(self, output):
        # 处理输出内容，移除空格和换行符
        processed_output = output.replace(' ', '').replace('\r\n', '')
        
        # 将处理后的内容追加到version_info
        self.patch_info += processed_output
        
        # 检查是否包含终止字符
        if '>' in output or ']' in output:
            print(f'Patch info: {self.patch_info}')
            # 提取补丁信息
            patch_match = re.search(r'Patch\s*Version:\s*([\w\-\.]+)', self.patch_info)
            if not patch_match:
                # 尝试匹配PatchPackageVersion格式，确保在非版本号字符前停止匹配
                patch_match = re.search(r'PatchPackageVersion:(V\d+R\d+[\w]+?)(?:[^\w]|$)', self.patch_info)
            
            if patch_match:
                patch_version = patch_match.group(1)
                self.patch_value.setText(patch_version)
            else:
                self.patch_value.setText('无补丁')
            
            # 断开与终端输出信号的连接
            if hasattr(self, 'terminal') and self.terminal and self.terminal.connection_thread:
                self.patch_info = '' # 重置patch_info
                self.terminal.connection_thread.received.disconnect(self.handle_patch_output)
